package cn.tedu.ivos.vehicle.service.impl;

import cn.tedu.ivos.vehicle.mapper.VehicleMapper;
import cn.tedu.ivos.vehicle.pojo.dto.VehicleQuery;
import cn.tedu.ivos.vehicle.pojo.dto.VehicleSaveParam;
import cn.tedu.ivos.vehicle.pojo.entity.Vehicle;
import cn.tedu.ivos.vehicle.pojo.vo.VehicleVO;
import cn.tedu.ivos.vehicle.service.VehicleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class VehicleServiceImpl implements VehicleService {
    // 注入mapper
    @Autowired
    private VehicleMapper vehicleMapper;


    /**
     * 显示车辆全部的基本信息
     *
     * @param vehicleQuery
     * @return
     */
    @Override
    public List<VehicleVO> selectVehicle(VehicleQuery vehicleQuery) {
        List<VehicleVO> list = vehicleMapper.selectVehicle(vehicleQuery);
        return list;
    }

    /**
     * 新增车辆信息和修改车辆信息
     *
     * @param vehicleSaveParam
     */
    @Override
    public void saveVehicle(VehicleSaveParam vehicleSaveParam) {
        Vehicle vehicle = new Vehicle();
        BeanUtils.copyProperties(vehicleSaveParam, vehicle);
        // 判断是否有id，如果没有就是修改车辆，如果有就是新增车辆
        if (vehicle.getId() == null) {
            vehicle.setCreateTime(new Date());
            // 新增车辆默认状态为1空闲
            vehicle.setStatus("1");
            vehicleMapper.insert(vehicle);
        } else {
            vehicle.setUpdateTime(new Date());
            vehicleMapper.update(vehicle);
        }
    }

    /**
     * 删除车辆信息
     *
     * @param vehicleId
     */
    @Override
    public void deleteVehicle(Long vehicleId) {
        vehicleMapper.deleteById(vehicleId);
    }


    /**
     * 移除/解绑电子围栏
     *
     * @param vehicleId
     */
    @Override
    public void unbindVehicle(Long vehicleId) {
        log.debug("移除/解绑电子围栏业务id={}", vehicleId);
        Vehicle vehicle = new Vehicle();
        vehicle.setId(vehicleId);
        vehicle.setGeofenceBindStatus("0");
        //之前的update相关SQL中的if判断要求不为null值才更新
        //但现在这里的业务就要更新一个null值,需要给车辆解除与围栏的绑定关系
        //所以这里需要单独写一个mapper层的方法,给当前车辆的geofence_id值设置为null
        vehicle.setGeofenceId(null);
        vehicle.setUpdateTime(new Date());
        vehicleMapper.unbindVehicle(vehicle);
    }

    /**
     * 绑定车辆
     * @param geofenceId
     * @param vehicleId
     */
    @Override
    public void bindVehicle(Long geofenceId, Long vehicleId) {
        Vehicle vehicle = new Vehicle();
        vehicle.setId(vehicleId);
        vehicle.setGeofenceId(geofenceId);
        vehicle.setGeofenceBindStatus("1");
        vehicle.setUpdateTime(new Date());
        vehicleMapper.update(vehicle);
    }


}
